var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/imp/index.tsx
var imp_exports = {};
__export(imp_exports, {
  $ImpSdk: () => $ImpSdk
});
module.exports = __toCommonJS(imp_exports);
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var import_ConvertListHelp = require("./cpts/ConvertListHelp");
var import_FlowHelp = require("./cpts/FlowHelp");
var import_ShowCheckRuleInfo = require("./cpts/ShowCheckRuleInfo");
var import_SourceHelp = require("./cpts/SourceHelp");
var import_service = require("./service");
var $ImpSdk = {
  /**
   * 业务流帮助
   */
  async flowHelp({
    bizCode,
    bizType,
    orgId,
    tenantId,
    title,
    width,
    height,
    contractTypes
  }) {
    const result = await (0, import_service.getFlowList)({ bizCode, orgId, tenantId, bizType: bizType || 0, contractTypes });
    if (!result) {
      return [false, null];
    }
    if (result.length) {
      if (result.length === 1) {
        return [true, result[0]];
      }
      const { helpConfig } = (0, import_util.getGlobalConfig)().default;
      return new Promise((resolve) => {
        (0, import_functionalComponent.showModal)({
          title: title || "选择业务流",
          width: width || helpConfig.width,
          height: height || helpConfig.height,
          content: /* @__PURE__ */ React.createElement(import_FlowHelp.FlowHelp, { dataSource: result }),
          async onOk(ins) {
            const result2 = await ins.getApi().getResult();
            if (result2) {
              ins.destroy();
              resolve([true, result2]);
            }
          },
          onCancel(ins) {
            ins.destroy();
            resolve([false, {}]);
          }
        });
      });
    }
    return [false, null];
  },
  /**
   * 引用来源（imp拉）
   */
  async citeSource(params) {
    const errorReturn = [false, {}];
    const {
      title,
      btnMessage = true,
      width,
      height,
      bizCode,
      tableName,
      busData,
      flowCode,
      sourceBizCode,
      detailTables,
      autoFill = false,
      defaultSelectedKeys = []
    } = params;
    if (!bizCode) {
      import_util.iup.alert("参数错误");
      return errorReturn;
    }
    const { helpConfig } = (0, import_util.getGlobalConfig)().default;
    const [sourceTree, sourceNodes] = await (0, import_service.loadSourceTree)({ flowCode, bizCode, tableName, sourceBizCode });
    if (!sourceNodes.length) {
      if (btnMessage) {
        import_util.iup.alert(import_util.iup.isString(sourceTree) ? sourceTree : "未配置数据来源！");
      }
      return errorReturn;
    }
    const sourceId = sourceNodes[0].key;
    const {
      columns = [],
      queryItems = [],
      popupName,
      allowMultiSelect,
      popupMode,
      masterQueryItems,
      masterColumns,
      masterFormId,
      treeFieldConfig,
      treeField
    } = await (0, import_service.loadSourceConfig)({
      sourceId: sourceId.split("_")[1]
    });
    let modalTitle = title || "选择来源";
    if (sourceNodes.length <= 1) {
      modalTitle = popupName;
    }
    return new Promise((resolve) => {
      (0, import_functionalComponent.showModal)({
        title: modalTitle,
        width: width || helpConfig.width,
        height: height || helpConfig.height,
        content: /* @__PURE__ */ React.createElement(
          import_SourceHelp.SourceHelp,
          {
            sourceTree,
            detailTables,
            defaultSourceCfg: {
              columns,
              queryItems,
              sourceId,
              allowMultiSelect,
              popupMode,
              subTableTitle: popupName,
              masterQueryItems,
              masterColumns,
              masterFormId,
              treeFieldConfig,
              treeField
            },
            flowCode,
            busData,
            sourceCount: sourceNodes.length,
            defaultSelectedKeys
          }
        ),
        async onOk(ins) {
          const impData = await ins.getApi().getResult();
          if (impData) {
            ins.destroy();
            autoFill && import_util.iup.updateState((updater) => {
              var _a;
              (_a = updater.data) == null ? void 0 : _a.setProps((pd) => {
                const newData = { ...pd };
                Object.keys(newData).forEach((k) => {
                  var _a2;
                  if ((_a2 = impData[k]) == null ? void 0 : _a2.length) {
                    newData[k] = k.endsWith("VoList") ? (newData[k] || []).concat(impData[k]) : impData[k][0];
                  }
                });
                return newData;
              });
            });
            resolve([true, impData]);
          }
        },
        onCancel(ins) {
          ins.destroy();
          resolve(errorReturn);
        }
      });
    });
  },
  /**
   * 生成目的单（imp推）
   */
  async pushBill(params) {
    const {
      flowCode: paramFlowCode,
      bizCode,
      instanceId,
      bizId,
      orgId,
      tenantId,
      width,
      height,
      title,
      targetBizCode,
      autoOpen = false,
      contractTypes,
      tableType
    } = params;
    let flowCode = paramFlowCode;
    if (!flowCode) {
      const [rc, result2] = await $ImpSdk.flowHelp({
        bizCode,
        bizType: 1,
        orgId,
        tenantId,
        width,
        height,
        contractTypes,
        tableType
      });
      if (rc) {
        flowCode = result2.flowCode;
      }
    }
    if (!flowCode) {
      import_util.iup.alert("未配置生成目的单的业务流!");
      return [false, ""];
    }
    const [success, result] = await import_util.iup.request.bodyWithArray({
      url: "/iup-rule-engine/bizflow/rulebiz/findPushConversionList",
      data: {
        flowCode,
        bizCode,
        targetBizCode
      }
    });
    if (!success) {
      import_util.iup.alert(result);
      return [false, ""];
    }
    if (!result.length) {
      import_util.iup.alert("未配置生成目的单的转换关系！");
      return [false, ""];
    }
    let convertInfo = null;
    if (result.length > 1) {
      const [r, d] = await new Promise((resolve) => {
        const { helpConfig } = (0, import_util.getGlobalConfig)().default;
        (0, import_functionalComponent.showModal)({
          title: title || "选择单据转换关系",
          width: width || helpConfig.width,
          height: height || helpConfig.height,
          content: /* @__PURE__ */ React.createElement(import_ConvertListHelp.ConvertListHelp, { dataSource: result }),
          async onOk(ins) {
            const result2 = await ins.getApi().getResult();
            if (result2) {
              ins.destroy();
              resolve([true, result2]);
            }
          },
          onCancel(ins) {
            ins.destroy();
            resolve([false, void 0]);
          }
        });
      });
      if (r) {
        convertInfo = d;
      } else {
        return [false, "取消选择单据转换关系"];
      }
    } else {
      convertInfo = result[0];
    }
    const [s, data] = await import_util.iup.request.bodyWithArray({
      url: "/iup-rule-engine/bizflow/rulebiz/pushBillForOpen",
      data: {
        flowCode,
        instanceId,
        bizCode,
        bizId,
        ruleIdList: [convertInfo.id]
      }
    });
    const { generateTask, needUser } = await (0, import_service.checkGenerateTask)({ flowCode, bizCode, instanceId, bizId });
    if (generateTask) {
      const generateTaskParams = { flowCode, bizCode, bizId, instanceId };
      if (needUser) {
        const taskUserRows = await import_util.iup.external.openHelp({
          type: "UserHelp",
          title: "指定执行人"
        });
        generateTaskParams.userNos = !!(taskUserRows == null ? void 0 : taskUserRows.value) ? [taskUserRows.value] : [];
        if (!(taskUserRows == null ? void 0 : taskUserRows.value)) {
          return [false, []];
        }
      }
      const taskFlag = await (0, import_service.autoGenerateTask)(generateTaskParams);
      if (taskFlag) {
        import_util.iup.message("生成代办任务成功！", "success");
        return [true, []];
      }
      return [false, []];
    }
    if (s) {
      const list = import_util.iup.isArray(data) ? data : [data];
      const editUrlList = [];
      list.forEach((r) => {
        const editUrl = import_util.iup.handleUrl(r.editUrl, { cacheKey: r.cacheKey });
        if (autoOpen) {
          import_util.iup.open(editUrl, { AppTitle: `${convertInfo.targetBizName}_新增`, oType: import_util.OType.Add });
        }
        editUrlList.push(editUrl);
      });
      return [true, editUrlList];
    } else {
      import_util.iup.alert(data);
      return [false, ""];
    }
  },
  /**
   * 获取推单据数据
   * @param cacheKey 单据数据缓存key
   * @returns
   */
  async getPushBillData({
    cacheKey,
    autoFill = false
  } = {}) {
    const key = cacheKey || import_util.iup.getQueryValue("cacheKey");
    const [success, result] = await import_util.iup.request.postWithArray({
      url: `/iup-rule-engine/bizflow/rulebiz/getPushBillData`,
      data: {
        cacheKey: key
      }
    });
    if (success) {
      const impData = result.reduce((p, d) => {
        const tmp = { ...p, [d.tableName]: d.data };
        if (d.modelName) {
          tmp[d.modelName] = d.data;
        }
        return tmp;
      }, {});
      autoFill && import_util.iup.updateState((updater) => {
        var _a;
        (_a = updater.data) == null ? void 0 : _a.setProps((pd) => {
          const newData = { ...pd };
          Object.keys(newData).forEach((k) => {
            var _a2;
            if ((_a2 = impData[k]) == null ? void 0 : _a2.length) {
              newData[k] = k.endsWith("VoList") ? impData[k] : impData[k][0];
            }
          });
          return newData;
        });
      });
      return impData;
    }
    import_util.iup.alert(result);
    return {};
  },
  /**
   * 业务流实例查看
   */
  showFlowInstance(params) {
    const { appTitle, bizCode, bizId, instanceId } = params;
    if (!instanceId && (!bizCode || !bizId)) {
      import_util.iup.alert("参数错误，业务类型和业务主键不能为空！");
      return;
    }
    if (!instanceId) {
      import_util.iup.alert("参数错误，流程实例不能为空！");
      return;
    }
    import_util.iup.open("/business/flowmanage/detail", {
      microAppName: "bre",
      AppTitle: appTitle || "业务流实例查看",
      oType: import_util.OType.View,
      instanceId,
      bizCode,
      id: bizId
    });
  },
  /**
     * 来源引用引用数据时支持不弹出数据选择窗口，直接返回所有数据
  
     */
  async mappingAllDatas(params) {
    const [success, result] = await import_util.iup.request.bodyWithArray({
      url: "/iup-rule-engine/helpInfo/mappingAllDatas",
      data: {
        ...params
      }
    });
    if (!success) {
      import_util.iup.alert(result);
      return [false, ""];
    } else if (success) {
      const list = import_util.iup.isArray(result) ? result : [result];
      return [true, list];
    }
    return [false, null];
  },
  /**
   * 校验规则提示窗
   */
  showCheckRuleInfo({ dataSource, isView, saveDraft, onContinue, title, width, height }) {
    const { helpConfig } = (0, import_util.getGlobalConfig)().default;
    const updatedData = dataSource == null ? void 0 : dataSource.map((item) => ({
      ...item,
      returnTips: item.returnTips.map((tip) => ({
        ...tip,
        ruleName: item.ruleName,
        ruleFlag: item.ruleFlag
      }))
    }));
    const returnTips = updatedData.flatMap((item) => item.returnTips);
    const hasForbiddenRule = returnTips.some((item) => item.retFlag === "forbid");
    const hasIgnoreRule = returnTips.every((item) => item.retFlag === "ignore");
    if (hasIgnoreRule && !isView) {
      return "无需弹窗";
    }
    return new Promise((resolve) => {
      const ins = (0, import_functionalComponent.showModal)({
        title: title || "业务管控规则",
        width: width || helpConfig.width,
        height: height || helpConfig.height,
        content: /* @__PURE__ */ React.createElement(import_ShowCheckRuleInfo.ShowCheckRuleInfo, { dataSource: returnTips }),
        footer: isView ? /* @__PURE__ */ React.createElement(
          "div",
          {
            style: {
              display: "flex",
              alignItems: "center",
              justifyContent: "flex-end",
              padding: "16px"
            }
          },
          /* @__PURE__ */ React.createElement(
            import_functionalComponent.Button,
            {
              type: "primary",
              style: { marginLeft: 10 },
              onClick: () => {
                ins.destroy();
              }
            },
            "确认"
          )
        ) : true,
        footerRight: !hasForbiddenRule && /* @__PURE__ */ React.createElement(
          import_functionalComponent.Button,
          {
            type: "primary",
            style: { marginLeft: 10 },
            onClick: () => {
              onContinue && onContinue(ins);
            }
          },
          "继续"
        ),
        okText: "保存草稿",
        async onOk(ins2) {
          saveDraft && saveDraft(ins2);
        },
        onCancel(ins2) {
          ins2.destroy();
          resolve([false, void 0]);
        }
      });
    });
  },
  /**
   * 结束待办任务
   * @param params  { taskId: string }
   * @returns
   */
  async closeTaskByTaskId(params) {
    const { taskId } = params;
    if (!taskId)
      return true;
    const { code, data } = await import_util.iup.request.get({
      url: "/iup-rule-engine/flow/definition/closeTask",
      data: { taskId }
    });
    if (code !== 0) {
      import_util.iup.alert(data);
      return false;
    }
    return true;
  }
};
import_util.iup.registerExternal({
  getImpSdk() {
    return $ImpSdk;
  }
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  $ImpSdk
});
